package com.dayu.finecomm.handler;

import java.util.Map;

import com.dayu.finecomm.service.FCService;
import com.dayu.finecomm.source.CollectSource;
import com.dayu.finecomm.utils.Helpers;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;

/**
 * @ClassName: TCPHandler
 * @Description: 1. PPP\RRR\MMM 报文解析器 <br/>
 *               2. CMD报文接收器
 * @author: 戴卫国
 * @date: 2018年2月23日 下午3:07:05
 * 
 * @Copyright: 2018 dayu Inc. All rights reserved.
 */
@Sharable
public class TCPHandler extends ChannelDuplexHandler {

	Map<String, ChannelHandlerContext> listeners;
	CollectSource source;

	public TCPHandler(CollectSource source, Map<String, ChannelHandlerContext> listeners) {

		this.listeners = listeners;
		this.source = source;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

		// ctx.pipeline().addLast(new CMDReceiveHandler());
		// ctx.pipeline().addLast(new CMDStoreHandler(source));

		String host = Helpers.host(ctx);

		if (listeners.containsKey(host)) {
			FCService.reduceClient(host);
			ctx.close();
		}
		listeners.put(host, ctx);
		FCService.addClient(host);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {

		FCService.reduceClient(Helpers.host(ctx));
		listeners.remove(Helpers.host(ctx));
		ctx.close();

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

		FCService.reduceClient(Helpers.host(ctx));
		listeners.remove(Helpers.host(ctx));
		ctx.close();
	}
}
